// 新建一个 Controller 类，比如 DeepseekController.java
package com.qcby.llmtchstd.controller;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qcby.llmtchstd.common.ResponseResult;
import com.qcby.llmtchstd.dao.ClassDao;
import com.qcby.llmtchstd.entity.*;
import com.qcby.llmtchstd.service.*;
import com.qcby.llmtchstd.utils.LLMClient;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/deepseek")
public class DeepseekController {
    @Autowired
    private UserChatService userChatService;
    @Autowired
    private TeachingPlanService teachingPlanService;
    @Autowired
    private ExamService examService;
    @Autowired
    private NoteService noteService;
    @Autowired
    private StudentService studentService;


    // 与前端 AJAX 的 url 对应
    @PostMapping("/chat")
    public Map<String, Object> chatWithDeepseek(@RequestBody Map<String, String> request,  HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        Message usermsg = new Message();
        Message aimsg = new Message();
        User user = (User)session.getAttribute("loginUser");
        try {
            // 1. 获取前端传递的用户消息
            String userMessage = request.get("content");
            System.out.println("userMessage:------"+userMessage);
            // 2. 调用大模型 API（使用你之前的 LLMClient 工具类）
            String llmResponse = LLMClient.getLLMResponse(userMessage);
            usermsg.setContent(userMessage);
            usermsg.setSendTime(LocalDateTime.now());
            usermsg.setSenderId(user.getId());
            usermsg.setReceiverType("ai");
            if(user.getType() == 0){
                usermsg.setSenderType("student");
            }else{
                usermsg.setSenderType("teacher");
            }
            System.out.println("usermsg:----------"+usermsg);
            userChatService.chatSave(usermsg);
            // 3. 解析大模型返回的 JSON（根据实际格式调整）
            // 这里假设你已经解析出纯文本回复内容
            String aiReply = parseLLMResponse(llmResponse);
            System.out.println("aiReply:------"+aiReply);
            aimsg.setReceiverType(usermsg.getSenderType());
            aimsg.setSendTime(LocalDateTime.now());
            aimsg.setContent(aiReply);
            aimsg.setSenderId(-1);
            aimsg.setSenderType("ai");
            aimsg.setReceiverId(usermsg.getSenderId());
            userChatService.chatSave(aimsg);
            // 4. 返回给前端
            response.put("code", "0000");
            response.put("data", aiReply); // 前端需要的 AI 回复内容
        } catch (Exception e) {
            response.put("code", "9999");
            response.put("msg", "调用失败：" + e.getMessage());
        }
        return response;
    }

    // 解析大模型返回的 JSON 响应（根据实际 API 格式实现）
    private String parseLLMResponse(String json) {
        try {
            // 方法1: 使用Gson类解析
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(json, JsonObject.class);

            // 方法2: 使用JsonParser的静态方法(如果Gson版本支持)
            // JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();

            // 提取AI回复内容
            return jsonObject.getAsJsonArray("choices")
                    .get(0).getAsJsonObject()
                    .getAsJsonObject("message")
                    .get("content")
                    .getAsString();
        } catch (Exception e) {
            throw new RuntimeException("解析AI响应失败: " + e.getMessage());
        }
    }


    @PostMapping("/generate-teaching-plan")
    public Map<String, Object> generateTeachingPlan(@RequestBody Map<String, String> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User user = (User) session.getAttribute("loginUser");

        try {
            String prompt = request.get("prompt");
            String aiPrompt = "你是一位经验丰富的教师，请根据以下要求生成一份详细的教学教案：\n" +
                    prompt + "\n\n" +
                    "教案必须以严格的JSON格式返回，包含以下字段：\n" +
                    "{\n" +
                    "  \"name\": \"教案名称\",\n" +
                    "  \"goal\": \"教学目标\",\n" +
                    "  \"remark\": \"详细教学内容\",\n" +
                    "  \"isExam\": \"0或1\"\n" +
                    "}\n\n" +
                    "请确保只返回JSON格式内容，不要包含任何额外说明或标记。";

            String llmResponse = LLMClient.getLLMResponse(aiPrompt);
            String cleanJson = llmResponse.replace("```json", "").replace("```", "").trim();
            TeachingPlan plan = parseTeachingPlanResponse(cleanJson);
            plan.setTeacherId(user.getId());
            plan.setCreateTime(LocalDateTime.now());

            Gson gson = new Gson();
            response.put("code", "0000");
            response.put("data", gson.toJson(plan)); // 将 TeachingPlan 对象转换为 JSON 字符串
        } catch (Exception e) {
            response.put("code", "9999");
            response.put("msg", "AI生成教案失败：" + e.getMessage());
            e.printStackTrace();
        }

        return response;
    }

    private TeachingPlan parseTeachingPlanResponse(String json) {
        try {
            JsonParser parser = new JsonParser();
            JsonObject outerJson = parser.parse(json).getAsJsonObject();

            JsonObject firstChoice = outerJson.getAsJsonArray("choices")
                    .get(0).getAsJsonObject();
            String content = firstChoice.getAsJsonObject("message")
                    .get("content").getAsString();

            JsonObject jsonObject = parser.parse(content).getAsJsonObject();

            TeachingPlan plan = new TeachingPlan();
            plan.setName(jsonObject.has("name") ? jsonObject.get("name").getAsString() : "未命名教案");
            plan.setGoal(jsonObject.has("goal") ? jsonObject.get("goal").getAsString() : "无明确目标");
            plan.setRemark(jsonObject.has("remark") ? jsonObject.get("remark").getAsString() : "无备注内容");
            plan.setIsExam(jsonObject.has("isExam") ? jsonObject.get("isExam").getAsString() : "0");

            return plan;
        } catch (Exception e) {
            // 记录详细错误信息
            System.err.println("解析教学计划响应失败: " + json);
            e.printStackTrace();
            TeachingPlan defaultPlan = new TeachingPlan();
            defaultPlan.setName("AI生成教案");
            defaultPlan.setGoal("自动生成的教学目标");
            defaultPlan.setRemark("AI生成的教学内容");
            defaultPlan.setIsExam("0");
            return defaultPlan;
        }
    }


     //基于前端传递的教案内容和参数生成试卷
     //前端传递完整的 generateData JSON 数据，包含用户信息、题型数量、教案内容等
     @PostMapping("/generate-exam")
     public Map<String, Object> generateExamByData(@RequestBody Map<String, Object> request) {
         Map<String, Object> response = new HashMap<>();
         try {
             Map<String, Object> generateData = (Map<String, Object>) request.get("generateData");
             if (generateData == null) {
                 response.put("code", "9999");
                 response.put("msg", "缺少generateData参数");
                 return response;
             }

             int way = Integer.parseInt(generateData.get("way").toString());
             int creatorId = Integer.parseInt(generateData.get("creatorId").toString());
             String creatorType = generateData.get("creatorType").toString();
             int tpId = Integer.parseInt(generateData.get("createBy").toString());

             TeachingPlan teachingPlan = teachingPlanService.selectById(tpId);
             if (teachingPlan == null) {
                 response.put("code", "9999");
                 response.put("msg", "未找到ID为" + tpId + "的教案");
                 return response;
             }

             int choiceCount = Integer.parseInt(generateData.get("choiceCount").toString());
             int fillCount = Integer.parseInt(generateData.get("fillCount").toString());
             int judgeCount = Integer.parseInt(generateData.get("judgeCount").toString());
             int essayCount = Integer.parseInt(generateData.get("essayCount").toString());
             int calculateCount = Integer.parseInt(generateData.get("calculateCount").toString());
             String examRemark = generateData.getOrDefault("remark", "").toString();

             if (choiceCount < 0 || fillCount < 0 || judgeCount < 0 || essayCount < 0 || calculateCount < 0) {
                 response.put("code", "9999");
                 response.put("msg", "题型数量不能为负数");
                 return response;
             }

             if (choiceCount + fillCount + judgeCount + essayCount + calculateCount == 0) {
                 response.put("code", "9999");
                 response.put("msg", "请至少设置一种题型的数量");
                 return response;
             }

             String examPrompt = buildExamPromptByData(
                     teachingPlan.getName(),
                     teachingPlan.getGoal(),
                     teachingPlan.getRemark(),
                     examRemark,
                     choiceCount, fillCount, judgeCount, essayCount, calculateCount
             );

             String llmResponse = LLMClient.getLLMResponse2(examPrompt, "");
             System.out.println("AI返回的试卷原始数据: " + llmResponse);

             // 关键修复：先提取message中的content内容
             JsonObject rootObject = JsonParser.parseString(llmResponse).getAsJsonObject();
             String examContent = rootObject.getAsJsonArray("choices")
                     .get(0).getAsJsonObject()
                     .getAsJsonObject("message")
                     .get("content")
                     .getAsString();

             // 再解析试卷内容JSON
             Exam exam = parseExamResponse(examContent);

             exam.setExamName(teachingPlan.getName() + "测试卷");
             exam.setCreatorId(creatorId);
             exam.setCreatorType(Integer.valueOf(creatorType));
             exam.setCreateBy(tpId);
             exam.setDescription("基于教案《" + teachingPlan.getName() + "》生成：" + examRemark);

             if (way == 0) {
                 exam.setCreateTime(LocalDateTime.now());
                 examService.generateAll(exam);
                 response.put("msg", "试卷生成成功");
             } else if (way == 1) {
                 int examId = Integer.parseInt(generateData.get("id").toString());
                 exam.setId(examId);
                 examService.generate(exam);
                 response.put("msg", "试卷更新成功");
             } else {
                 response.put("code", "9999");
                 response.put("msg", "way参数错误（0=插入，1=更新）");
                 return response;
             }

             response.put("code", "0000");
             response.put("data", exam);

         } catch (Exception e) {
             response.put("code", "9999");
             response.put("msg", "操作失败：" + e.getMessage());
             e.printStackTrace();
         }
         return response;
     }

    private String buildExamPromptByData(
            String planName, String planGoal, String planContent, String planRemark,
            int choiceCount, int fillCount, int judgeCount, int essayCount, int calculateCount
    ) {
        StringBuilder questionCountDesc = new StringBuilder();
        if (choiceCount > 0) questionCountDesc.append("- 选择题：").append(choiceCount).append("题，每题分值建议2-5分\n");
        if (fillCount > 0) questionCountDesc.append("- 填空题：").append(fillCount).append("题，每题分值建议3-4分\n");
        if (judgeCount > 0) questionCountDesc.append("- 判断题：").append(judgeCount).append("题，每题分值建议2分\n");
        if (essayCount > 0) questionCountDesc.append("- 简答题：").append(essayCount).append("题，每题分值建议5-8分\n");
        if (calculateCount > 0) questionCountDesc.append("- 计算题/解答题：").append(calculateCount).append("题，每题分值建议6-10分\n");

        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一位严格按照要求执行任务的专业学科教师，现在需要根据以下教案内容生成标准化测试试卷。\n\n")
                .append("【重要警告】本任务有严格格式要求，不遵守将导致任务失败！\n")
                .append("【教案信息】\n")
                .append("教案名称：").append(planName).append("\n")
                .append("教学目标：").append(planGoal).append("\n")
                .append("核心教学内容：").append(planContent).append("\n")
                .append("额外备注：").append(planRemark).append("\n\n")
                .append("【试卷要求】\n")
                .append("1. 题型及数量必须严格遵循以下要求，不允许多生成或少生成：\n")
                .append(questionCountDesc)
                .append("\n2. 所有题目必须紧扣教案的教学目标和核心内容，难度与教学内容匹配，避免超纲内容。\n")
                .append("3. 必须以JSON格式返回，字段和格式严格匹配以下结构，不允许任何额外文字、解释或格式标记（如```json）：\n")
                .append("{\n")
                .append("  \"choiceQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"题干内容\",\"score\":3,\"options\":[\"A.选项1\",\"B.选项2\",\"C.选项3\",\"D.选项4\"],\"answer\":\"A\"},\n")
                .append("    ...（共").append(choiceCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"fillQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"Java中定义类的关键字是______\",\"score\":3,\"answer\":\"class\"},\n")
                .append("    ...（共").append(fillCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"judgeQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"Java是解释型语言\",\"score\":2,\"answer\":\"false\",\"analysis\":\"Java是半编译半解释型语言\"},\n")
                .append("    ...（共").append(judgeCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"essayQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"简述Spring Boot自动配置原理\",\"score\":6,\"answer\":\"通过@EnableAutoConfiguration注解实现\"},\n")
                .append("    ...（共").append(essayCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"calculateQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"计算3x+5当x=2时的值\",\"score\":5,\"answer\":\"11\",\"steps\":[\"1.代入x=2：3×2+5\",\"2.计算得11\"]},\n")
                .append("    ...（共").append(calculateCount).append("题，数量必须精确）\n")
                .append("  ]\n")
                .append("}\n\n")
                .append("【强制要求】\n")
                .append("- 对于数量为0的题型，仍需保留该字段，但值为空数组[]\n")
                .append("- 所有字段必须存在，不允许省略任何字段\n")
                .append("- JSON格式必须正确，可直接被解析，使用双引号，逗号分隔正确\n")
                .append("- 确保每个题型的数量与要求完全一致\n")
                .append("- 答案必须准确无误，符合教案教学内容");

        return prompt.toString();
    }

    private Exam parseExamResponse(String json) {
        try {
            String cleanJson = json.replace("```json", "").replace("```", "").trim();
            JsonObject jsonObject = JsonParser.parseString(cleanJson).getAsJsonObject();

            Exam exam = new Exam();

            exam.setChoiceQuestions(getJsonFieldAsString(jsonObject, "choiceQuestions", "[]"));
            exam.setFillQuestions(getJsonFieldAsString(jsonObject, "fillQuestions", "[]"));
            exam.setJudgeQuestions(getJsonFieldAsString(jsonObject, "judgeQuestions", "[]"));
            exam.setEssayQuestions(getJsonFieldAsString(jsonObject, "essayQuestions", "[]"));
            exam.setCalculateQuestions(getJsonFieldAsString(jsonObject, "calculateQuestions", "[]"));

            return exam;
        } catch (Exception e) {
            System.err.println("解析试卷响应失败: " + json);
            e.printStackTrace();
            throw new RuntimeException("解析试卷内容失败: " + e.getMessage());
        }
    }

    private String getJsonFieldAsString(JsonObject jsonObject, String fieldName, String defaultValue) {
        try {
            if (jsonObject == null) {
                return defaultValue;
            }

            if (!jsonObject.has(fieldName)) {
                System.err.println("JSON字段[" + fieldName + "]不存在，使用默认值: " + defaultValue);
                return defaultValue;
            }

            JsonElement element = jsonObject.get(fieldName);
            if (element.isJsonNull()) {
                System.err.println("JSON字段[" + fieldName + "]值为null，使用默认值: " + defaultValue);
                return defaultValue;
            }

            return element.toString();
        } catch (Exception e) {
            System.err.println("获取JSON字段[" + fieldName + "]失败: " + e.getMessage());
            return defaultValue;
        }
    }

    @PostMapping("/generate-exam-from-note")
    public Map<String, Object> generateExamByNote(@RequestBody Map<String, Object> request) {

        Map<String, Object> response = new HashMap<>();
        try {
            Map<String, Object> generateData = (Map<String, Object>) request.get("generateData");
            if (generateData == null) {
                response.put("code", "9999");
                response.put("msg", "缺少generateData参数");
                return response;
            }
            System.out.println("generateData:"+generateData.toString());
            int way = Integer.parseInt(generateData.get("way").toString());
            int creatorId = Integer.parseInt(generateData.get("creatorId").toString());
            String creatorType = generateData.get("creatorType").toString();
            int noteId = Integer.parseInt(generateData.get("createBy").toString());

            // 获取笔记内容
            ResponseResult noteResult = noteService.selectById(noteId);
            if (noteResult == null || !"0000".equals(noteResult.getCode())) {
                response.put("code", "9999");
                response.put("msg", "未找到ID为" + noteId + "的笔记");
                return response;
            }
            Note note = (Note) noteResult.getData();

            int choiceCount = Integer.parseInt(generateData.get("choiceCount").toString());
            int fillCount = Integer.parseInt(generateData.get("fillCount").toString());
            int judgeCount = Integer.parseInt(generateData.get("judgeCount").toString());
            int essayCount = Integer.parseInt(generateData.get("essayCount").toString());
            int calculateCount = Integer.parseInt(generateData.get("calculateCount").toString());
            String examRemark = generateData.getOrDefault("remark", "").toString();

            if (choiceCount < 0 || fillCount < 0 || judgeCount < 0 || essayCount < 0 || calculateCount < 0) {
                response.put("code", "9999");
                response.put("msg", "题型数量不能为负数");
                return response;
            }

            if (choiceCount + fillCount + judgeCount + essayCount + calculateCount == 0) {
                response.put("code", "9999");
                response.put("msg", "请至少设置一种题型的数量");
                return response;
            }

            String examPrompt = buildExamPromptByNote(
                    note.getName(),
                    note.getContent(),
                    examRemark,
                    choiceCount, fillCount, judgeCount, essayCount, calculateCount
            );

            String llmResponse = LLMClient.getLLMResponse2(examPrompt, "");
            System.out.println("AI返回的试卷原始数据: " + llmResponse);

            // 提取message中的content内容
            JsonObject rootObject = JsonParser.parseString(llmResponse).getAsJsonObject();
            String examContent = rootObject.getAsJsonArray("choices")
                    .get(0).getAsJsonObject()
                    .getAsJsonObject("message")
                    .get("content")
                    .getAsString();

            // 解析试卷内容JSON
            Exam exam = parseExamResponse(examContent);
            exam.setExamName(note.getName() + "测试卷");
            exam.setCreatorId(creatorId);
            exam.setCreatorType(Integer.valueOf(creatorType));
            exam.setCreateBy(noteId);
            exam.setDescription("基于笔记《" + note.getName() + "》生成：" + examRemark);
            exam.setExamDuration((Integer) generateData.get("examDuration"));
            String releaseTimeStr = (String) generateData.get("releaseTime");

// 定义时间格式（与字符串格式匹配，这里是 "yyyy-MM-dd'T'HH:mm"）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");

// 解析字符串为 LocalDateTime
            LocalDateTime releaseTime = LocalDateTime.parse(releaseTimeStr, formatter);

// 设置到对象中
            exam.setReleaseTime(releaseTime);
            if (way == 0) {
                exam.setCreateTime(LocalDateTime.now());
                examService.generateAlll(exam);
                response.put("msg", "试卷生成成功");
            } else if (way == 1) {
                int examId = Integer.parseInt(generateData.get("id").toString());
                exam.setId(examId);
                examService.generate(exam);
                response.put("msg", "试卷更新成功");
            } else {
                response.put("code", "9999");
                response.put("msg", "way参数错误（0=插入，1=更新）");
                return response;
            }

            response.put("code", "0000");
            response.put("data", exam);

        } catch (Exception e) {
            response.put("code", "9999");
            response.put("msg", "操作失败：" + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    private String buildExamPromptByNote(
            String noteName, String noteContent, String examRemark,
            int choiceCount, int fillCount, int judgeCount, int essayCount, int calculateCount
    ) {
        StringBuilder questionCountDesc = new StringBuilder();
        if (choiceCount > 0) questionCountDesc.append("- 选择题：").append(choiceCount).append("题，每题分值建议2-5分\n");
        if (fillCount > 0) questionCountDesc.append("- 填空题：").append(fillCount).append("题，每题分值建议3-4分\n");
        if (judgeCount > 0) questionCountDesc.append("- 判断题：").append(judgeCount).append("题，每题分值建议2分\n");
        if (essayCount > 0) questionCountDesc.append("- 简答题：").append(essayCount).append("题，每题分值建议5-8分\n");
        if (calculateCount > 0) questionCountDesc.append("- 计算题/解答题：").append(calculateCount).append("题，每题分值建议6-10分\n");

        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一位严格按照要求执行任务的专业学科教师，现在需要根据以下学生笔记内容生成标准化测试试卷。\n\n")
                .append("【重要警告】本任务有严格格式要求，不遵守将导致任务失败！\n")
                .append("【笔记信息】\n")
                .append("笔记名称：").append(noteName).append("\n")
                .append("笔记内容：").append(noteContent).append("\n")
                .append("额外备注：").append(examRemark).append("\n\n")
                .append("【试卷要求】\n")
                .append("1. 题型及数量必须严格遵循以下要求，不允许多生成或少生成：\n")
                .append(questionCountDesc)
                .append("\n2. 所有题目必须紧扣笔记的核心内容，难度适中，避免超纲内容。\n")
                .append("3. 必须以JSON格式返回，字段和格式严格匹配以下结构，不允许任何额外文字、解释或格式标记（如```json）：\n")
                .append("{\n")
                .append("  \"choiceQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"题干内容\",\"score\":3,\"options\":[\"A.选项1\",\"B.选项2\",\"C.选项3\",\"D.选项4\"],\"answer\":\"A\"},\n")
                .append("    ...（共").append(choiceCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"fillQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"Java中定义类的关键字是______\",\"score\":3,\"answer\":\"class\"},\n")
                .append("    ...（共").append(fillCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"judgeQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"Java是解释型语言\",\"score\":2,\"answer\":\"false\",\"analysis\":\"Java是半编译半解释型语言\"},\n")
                .append("    ...（共").append(judgeCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"essayQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"简述Spring Boot自动配置原理\",\"score\":6,\"answer\":\"通过@EnableAutoConfiguration注解实现\"},\n")
                .append("    ...（共").append(essayCount).append("题，数量必须精确）\n")
                .append("  ],\n")
                .append("  \"calculateQuestions\": [\n")
                .append("    {\"id\":1,\"content\":\"计算3x+5当x=2时的值\",\"score\":5,\"answer\":\"11\",\"steps\":[\"1.代入x=2：3×2+5\",\"2.计算得11\"]},\n")
                .append("    ...（共").append(calculateCount).append("题，数量必须精确）\n")
                .append("  ]\n")
                .append("}\n\n")
                .append("【强制要求】\n")
                .append("- 对于数量为0的题型，仍需保留该字段，但值为空数组[]\n")
                .append("- 所有字段必须存在，不允许省略任何字段\n")
                .append("- JSON格式必须正确，可直接被解析，使用双引号，逗号分隔正确\n")
                .append("- 确保每个题型的数量与要求完全一致\n")
                .append("- 答案必须准确无误，符合笔记教学内容");

        return prompt.toString();
    }

    @PostMapping("/analyze-student")
    public Map<String, Object> analyzeStudent(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();

        try {
            String studentIdStr = request.get("studentId").toString();
            Integer studentId = Integer.parseInt(studentIdStr);

            // 调用学生服务获取完整学生信息（包括班级信息）
            ResponseResult studentResult = studentService.getStudentDetails(studentId);
            if (!"0000".equals(studentResult.getCode())) {
                response.put("code", "9999");
                response.put("msg", "获取学生信息失败");
                return response;
            }

            Student student = (Student) studentResult.getData();

            // 构建AI分析提示
            StringBuilder prompt = new StringBuilder();
            prompt.append("你是一位经验丰富的教育专家，请对以下学生进行全面的学习分析：\n");
            prompt.append("学生ID：").append(student.getId()).append("\n");
            prompt.append("姓名：").append(student.getName()).append("\n");
            prompt.append("班级：").append(student.getClassName()).append("\n");
            prompt.append("性别：").append(student.getSex()).append("\n");
            prompt.append("年龄：").append(student.getAge()).append("\n");
            prompt.append("学号：").append(student.getSno()).append("\n\n");

            prompt.append("请从以下几个方面进行分析：\n");
            prompt.append("1. 学习习惯评估\n");
            prompt.append("2. 潜在优势分析\n");
            prompt.append("3. 可能存在的学习问题\n");
            prompt.append("4. 个性化学习建议\n");
            prompt.append("5. 未来发展方向预测\n\n");
            prompt.append("要求：\n");
            prompt.append("- 分析结果要详细、专业\n");
            prompt.append("- 给出具体可执行的建议\n");
            prompt.append("- 使用中文输出\n");
            prompt.append("- 格式清晰，分点列出");

            // 调用大模型API
            String llmResponse = LLMClient.getLLMResponse(prompt.toString());
            String analysisResult = parseLLMResponse(llmResponse);

            response.put("code", "0000");
            response.put("data", analysisResult);
        } catch (Exception e) {
            response.put("code", "9999");
            response.put("msg", "AI分析失败：" + e.getMessage());
            e.printStackTrace();
        }

        return response;
    }

    @PostMapping("/download-analysis")
    public ResponseEntity<byte[]> downloadAnalysisReport(@RequestBody Map<String, Object> request) throws IOException {
        // 1. 获取请求数据
        Map<String, Object> studentInfo = (Map<String, Object>) request.get("studentInfo");
        String analysisContent = (String) request.get("analysisContent");

        // 2. 验证数据
        if (studentInfo == null || analysisContent == null) {
            throw new IllegalArgumentException("缺少必要的请求参数");
        }

        String studentName = (String) studentInfo.get("name");
        String studentId = (String) studentInfo.get("id");
        String studentClass = (String) studentInfo.get("class");

        // 3. 创建Word文档
        try (XWPFDocument document = new XWPFDocument()) {
            // 3.1 添加标题
            XWPFParagraph titlePara = document.createParagraph();
            titlePara.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun titleRun = titlePara.createRun();
            titleRun.setText("AI学习分析报告");
            titleRun.setBold(true);
            titleRun.setFontSize(18);

            // 3.2 添加学生基本信息
            addStudentInfoSection(document, studentName, studentId, studentClass);

            // 3.3 添加分析内容
            addAnalysisContent(document, analysisContent);

            // 3.4 添加页脚
            addFooter(document);

            // 4. 将文档转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.write(baos);

            // 5. 设置响应头
            String fileName = String.format("%s-AI分析报告-%s.docx",
                    studentName,
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));


            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(baos.toByteArray());
        }
    }

    private void addStudentInfoSection(XWPFDocument document, String name, String id, String className) {
        XWPFParagraph infoPara = document.createParagraph();
        infoPara.setAlignment(ParagraphAlignment.LEFT);

        XWPFRun infoRun = infoPara.createRun();
        infoRun.setText("学生姓名: " + name);
        infoRun.addBreak();
        infoRun.setText("学号: " + id);
        infoRun.addBreak();
        infoRun.setText("班级: " + className);
        infoRun.addBreak();
        infoRun.addBreak();
    }

    private void addAnalysisContent(XWPFDocument document, String content) {
        // 按段落分割内容
        String[] paragraphs = content.split("\n\n");

        for (String para : paragraphs) {
            if (para.trim().isEmpty()) continue;

            XWPFParagraph docPara = document.createParagraph();
            docPara.setAlignment(ParagraphAlignment.LEFT);
            docPara.setSpacingAfter(200); // 段落间距

            XWPFRun run = docPara.createRun();

            // 判断是否是标题行
            if (para.startsWith("【") && para.endsWith("】")) {
                run.setText(para);
                run.setBold(true);
                run.setFontSize(14);
            } else {
                run.setText(para);
                run.setFontSize(12);
            }
        }
    }

    private void addFooter(XWPFDocument document) {
        XWPFParagraph footerPara = document.createParagraph();
        footerPara.setAlignment(ParagraphAlignment.RIGHT);

        XWPFRun footerRun = footerPara.createRun();
        footerRun.setText("生成时间: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        footerRun.setItalic(true);
        footerRun.setFontSize(10);
    }

    @PostMapping("/analyze-student-teacher")
    public Map<String, Object> analyzeStudentWithTeacherDetail(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();

        try {
            String studentIdStr = (String) request.get("studentId");
            Integer studentId = Integer.parseInt(studentIdStr);
            String studentName = (String) request.get("studentName");
            String studentClass = (String) request.get("studentClass");
            String studentAge = request.get("studentAge") != null ? request.get("studentAge").toString() : "未知";
            String studentGender = request.get("studentGender") != null ? request.get("studentGender").toString() : "未知";

            // 获取考试成绩数据
            List<Map<String, Object>> examResults = (List<Map<String, Object>>) request.get("examResults");

            // 构建更详细的AI分析提示
            StringBuilder prompt = new StringBuilder();
            prompt.append("你是一位经验丰富的教育专家，请对以下学生进行全面的学习分析：\n");
            prompt.append("学生ID：").append(studentId).append("\n");
            prompt.append("姓名：").append(studentName).append("\n");
            prompt.append("班级：").append(studentClass).append("\n");
            prompt.append("年龄：").append(studentAge).append("\n");
            prompt.append("性别：").append(studentGender).append("\n\n");

            if (examResults != null && !examResults.isEmpty()) {
                prompt.append("【考试成绩记录】\n");
                double totalScore = 0;
                double maxScore = Double.MIN_VALUE;
                double minScore = Double.MAX_VALUE;

                for (Map<String, Object> exam : examResults) {
                    int examId = (int) exam.get("examId");
                    int score = (int) exam.get("score");
                    totalScore += score;
                    maxScore = Math.max(maxScore, score);
                    minScore = Math.min(minScore, score);

                    prompt.append("- 考试ID: ").append(examId).append(", 得分: ").append(score).append("\n");
                }

                double averageScore = totalScore / examResults.size();
                prompt.append("\n统计信息:\n");
                prompt.append("- 平均分: ").append(String.format("%.2f", averageScore)).append("\n");
                prompt.append("- 最高分: ").append(maxScore).append("\n");
                prompt.append("- 最低分: ").append(minScore).append("\n");
                prompt.append("- 考试次数: ").append(examResults.size()).append("\n\n");
            } else {
                prompt.append("【注意】该学生暂无考试成绩记录\n\n");
            }

            prompt.append("请从以下几个方面进行分析：\n");
            prompt.append("1. 学习成绩趋势分析（基于考试成绩）\n");
            prompt.append("2. 学习习惯评估\n");
            prompt.append("3. 潜在优势分析\n");
            prompt.append("4. 可能存在的学习问题\n");
            prompt.append("5. 个性化学习建议（基于成绩分析）\n");
            prompt.append("6. 未来发展方向预测\n\n");
            prompt.append("要求：\n");
            prompt.append("- 分析结果要详细、专业\n");
            prompt.append("- 结合考试成绩数据给出具体分析\n");
            prompt.append("- 给出具体可执行的建议\n");
            prompt.append("- 使用中文输出\n");
            prompt.append("- 格式清晰，分点列出");

            // 调用AI接口
            String llmResponse = LLMClient.getLLMResponse(prompt.toString());
            String analysisResult = parseLLMResponse(llmResponse);

            response.put("code", "0000");
            response.put("data", analysisResult);
        } catch (Exception e) {
            response.put("code", "9999");
            response.put("msg", "AI分析失败：" + e.getMessage());
            e.printStackTrace();
        }

        return response;
    }
}